package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${out_put_path}")
    private String outputpath;

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private SetmealDao setmealDao;

    @Override
    public void add(Integer[] checkgroupIds, Setmeal setmeal) {
        //`t_setmeal`表中添加套餐
        setmealDao.add(setmeal);

        //`t_setmeal_checkgroup`表中添加checkgroup_id,setmeal_id
        if (checkgroupIds != null && checkgroupIds.length > 0){
            setCheckGroupIdAndSetmealId(checkgroupIds,setmeal.getId());
        }

        if (setmeal.getImg() != null){
            //保存完成套餐信息后将图片名称存储到redis集合中
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());
        }
        /*//新增套餐后需要重新生成静态页面
        generateMobileStaticHtml();*/

        //(添加一个套餐->生成一个静态页面)
        generateMobileStaticHtml(setmeal);
    }

    /**
     * 新增套餐后需要重新生成静态页面
     */
    /*private void generateMobileStaticHtml() {
        //准备模板文件中所需的数据
        List<Setmeal> setmeals = setmealDao.findAllSetMeal();

        //1)生成套餐列表静态页面
        generateMobileSetmealListHtml(setmeals);
        //2)生成套餐详情静态页面（多个）
        generateMobileSetmealDetailHtml(setmeals);
    }*/

    private void generateMobileStaticHtml(Setmeal setmeal) {
        //准备模板文件中所需的数据
        List<Setmeal> setmeals = setmealDao.findAllSetMeal();

        //1)生成套餐列表静态页面
        generateMobileSetmealListHtml(setmeals);
        //2)生成套餐详情静态页面（多个）
        /*generateMobileSetmealDetailHtml(setmeals);*/
        //2)生成套餐详情静态页面（单个）
        generateMobileSetmealDetailHtml(setmeal);
    }
    /**
     * //1)生成套餐列表静态页面
     * @param setmeals
     */
    private void generateMobileSetmealListHtml(List<Setmeal> setmeals) {
        //准备生成静态页面方法所需数据
        String templateName = "mobile_setmeal.ftl";
        String htmlPageName = "m_setmeal.html";
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("setmealList",setmeals);
        //生成静态页面(通用)
        generateHtml(templateName,htmlPageName,dataMap);
    }

    /**
     * //2)生成套餐详情静态页面（多个）
     * @param setmeals
     */
    private void generateMobileSetmealDetailHtml(List<Setmeal> setmeals) {
        //准备生成静态页面方法所需数据
        String templateName = "mobile_setmeal_detail.ftl";
        for (Setmeal setmeal : setmeals) {
            String htmlPageName = "setmeal_detail_"+ setmeal.getId() +".html";
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("setmeal",setmealDao.findSetMealById(setmeal.getId()));
            //生成静态页面(通用)
            generateHtml(templateName,htmlPageName,dataMap);
        }
    }
    /**
     * //2)生成套餐详情静态页面（单个）
     * @param setmeal
     */
    private void generateMobileSetmealDetailHtml(Setmeal setmeal) {
        //准备生成静态页面方法所需数据
        //1)模板名称
        String templateName = "mobile_setmeal_detail.ftl";
        //2)页面名称
        String htmlPageName = "setmeal_detail_"+ setmeal.getId() +".html";
        //3)数据Map集合
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("setmeal",setmealDao.findSetMealById(setmeal.getId()));
        generateHtml(templateName,htmlPageName,dataMap);
    }

    /**
     * 生成静态页面(通用)
     * @param templateName
     * @param htmlPageName
     * @param dataMap
     */
    public void generateHtml(String templateName,String htmlPageName,Map<String,Object> dataMap){
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out = null;
        try {
            Template template = configuration.getTemplate(templateName);
            String docFile = outputpath + "\\" + htmlPageName;
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
            template.process(dataMap,out);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != out){
                try {
                    out.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        PageHelper.startPage(currentPage, pageSize);
//        根据条件查询 套餐
        Page<Setmeal> page = setmealDao.selectSetmealByCondition(queryString);
        long total = page.getTotal();
        List<Setmeal> list = page.getResult();

        return new PageResult(total,list);
    }

    @Override
    public void delete(Integer id) {
        //1查询id在 [order]表 中对应条目数量
        Long count = setmealDao.findCountFromOrderBySetmealId(id);
        //1.1)数量>0,抛出运行异常:[存在预约与本套餐关联,无法删除]
        if (count > 0){
            throw new RuntimeException("存在预约与本套餐关联,无法删除");
        }else {
            //1.2)数量!>0,查询[t_setmeal_checkGroup]表是否存在 id 对应条目,存在则删除
            setmealDao.deleteBySetmealId(id);

            //先移除 redis set 集合中的图片名
            String picName = setmealDao.findPicById(id);
            if (picName != null && picName.length() > 0){
                jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_DB_RESOURCES,picName);
            }

            //1.2.1)删除[t_setmeal]表中 id 对应的条目
            setmealDao.deleteById(id);

            //删除静态对应的页面
            deleteMobileStaticHtml(id);
        }
    }

    private void deleteMobileStaticHtml(Integer id) {
        //一|生成套餐列表静态页面
        //1)准备所有套餐对象
        List<Setmeal> setmeals = setmealDao.findAllSetMeal();
        //2)生成套餐列表静态页面
        generateMobileSetmealListHtml(setmeals);

        //二|删除存放静态页面路径下的静态页面
        //1)获取文件路径
        String planFilePath = outputpath;
        //2)获取文件名
        String htmlPageName = "setmeal_detail_"+ id +".html";
        //3)获取全路径
        File allPath = new File(planFilePath + "/" + htmlPageName);
        //System.out.println(allPath);//@TEST
        //4)删除该文件
        if (allPath.exists()){
            if (allPath.isFile()){
                allPath.delete();
            }
        }
    }


    @Override
    public Setmeal findById(Integer id) {
        //通过id 查询[t_setmeal]表 对应条目
        Setmeal setmeal = setmealDao.findById(id);
        return setmeal;
    }

    @Override
    public List<CheckGroup> findAll() {
        //查询全部checkGroup
        List<CheckGroup> list = setmealDao.findAll();
        return list;
    }

    @Override
    public List<Integer> findCheckGroupBySetmealId(Integer id) {
        //根据 [套餐id] 查询与之关联的 [检查组id]
        List<Integer> list = setmealDao.findCheckGroupBySetmealId(id);
        return list;
    }

    @Override
    public void edit(Integer[] checkgroupIds, Setmeal setmeal) {
        //1修改[套餐]信息
        //1.1)Redis缓存中的数据 是否也要更改
        //1.1.1)拿取原先的 img 和 id
        Integer oldId = setmeal.getId();
        String newPicName = setmeal.getImg();
        if (newPicName != null && newPicName.length() > 0){
            //存在新传入的图片
            String oldPicName = setmealDao.findPicById(oldId);
            //移除原先 redis 中的旧数据
            if (oldPicName != null && oldPicName.length() > 0){
                jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_DB_RESOURCES,oldPicName);
            }
            //加入新的数据
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,newPicName);
        }
        //1.2)修改[t_setmeal]表
        setmealDao.editSetMeal(setmeal);

        //1.3)修改中间表[t_setmeal_checkgroup]
        //1.3.1)删除[t_setmeal_checkgroup]中所有与[套餐id]关联的数据
        setmealDao.deleteCheckGroupBySetmealId(oldId);
        //1.3.2)添加现有的[套餐]&[检查组]关联
        setCheckGroupIdAndSetmealId(checkgroupIds,oldId);

        //重新生成该套餐的静态页面
        editMobileStaticHtml(setmeal);
    }

    private void editMobileStaticHtml(Setmeal setmeal) {
        //一|生成套餐列表静态页面
        //1)准备所有套餐对象
        List<Setmeal> setmeals = setmealDao.findAllSetMeal();
        //2)生成套餐列表静态页面
        generateMobileSetmealListHtml(setmeals);

        //二|生成修改套餐的静态页面
        generateMobileSetmealDetailHtml(setmeal);
    }

    /**
     * //查询所有套餐信息
     * @return
     */
    @Override
    public List<Setmeal> findAllSetMeal() {
        //查询所有套餐信息
        List<Setmeal> list = setmealDao.findAllSetMeal();
        return list;
    }

    /**
     * 通过id查询完整套餐信息
     * @param id
     * @return
     */
    @Override
    public Setmeal findSetMealById(Integer id) {
        Setmeal setmeal = setmealDao.findSetMealById(id);
        return setmeal;
    }

    @Override
    public List<Map> getValueAndNameFromSetmeal() {
        //查询[t_setmeal]和[t_order]表的[套餐名称]和[数量]
        List<Map> setmealCount = setmealDao.getValueAndNameFromSetmeal();
        return setmealCount;
    }

    /**
     * //`t_setmeal_checkgroup`表中添加checkgroup_id,setmeal_id
     * @param checkgroupIds
     * @param setmeal_id
     */
    private void setCheckGroupIdAndSetmealId(Integer[] checkgroupIds, Integer setmeal_id) {
        for (Integer checkgroupId : checkgroupIds) {
            Map<String,Integer> map = new HashMap<>();
            map.put("setmeal_id",setmeal_id);
            map.put("checkgroup_id",checkgroupId);
            setmealDao.setCheckGroupIdAndSetmealId(map);
        }
    }
}
